<template>
    <div>
        <NavTop />
        <div style="width: 1400px;margin: auto;">
        <el-table
            ref="multipleTableRef"
            :data="cartData"
            style="width: 100%"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" :selectable="selectable" width="55" />
            <el-table-column property="id" label="商品编号" width="120" />
            <el-table-column property="name" label="商品名称" width="520" />
            <el-table-column property="price" label="商品价格"/>
            <el-table-column property="onlineprice" label="优惠价格" />
            <el-table-column property="num" label="数量" />
            <el-table-column property="total" label="总金额" />
            <el-table-column align="right">
            <template #header>
                <el-input v-model="search" size="small" placeholder="搜索" />
            </template>
            <template #default="scope">
                <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index)"
                >
                删除
                </el-button>
            </template>
            </el-table-column>
        </el-table>
        <div style="margin-right: 500px;">
            <el-button @click="buy()">购买</el-button>
        </div>
        </div>
    </div>
</template>

<script>
import NavTop from '../../components/NavTop'
import { userGoodsStore } from '@/store/goods';
import { ElMessage, ElMessageBox } from 'element-plus'
export default {
    components:{
        NavTop
    },
    data() {
        return {
            multipleTableRef:null,
            multipleSelection:[],
            store:userGoodsStore(),
            cartData:JSON.parse(sessionStorage.getItem('cart')),
            time:new Date(),
            orderID:'',
            search:''
        }
    },
    methods:{
        handleSelectionChange (val){
            this.multipleSelection = val
        },
        handleDelete(index){
            ElMessageBox.confirm(
                '确定要删除吗?',
                'Warning',
                {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                }
            )
                .then(() => {
                    this.cartData.splice(index,1)//把当前行数据进行删除，注意，我们只是在数组里面进行删除，sessionStorage里面没有变化
                    //更新session里面的数据
                    sessionStorage.setItem('cart',JSON.stringify(this.cartData))
                })
                .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '删除取消',
                })
                })
        },
        buy(){
            if (this.multipleSelection==''){
                ElMessageBox.alert('请选择要购买的商品','温馨提示', {
                confirmButtonText:'知道了',
                callback: () => {
                    ElMessage({
                        type: 'info',
                        message: 'ok',
                        })
                    },
                })
            } else {
            //打印订单号,看看是否OK
            this.orderID = this.time.getFullYear().toString() + (this.time.getMonth() + 1).toString() +
                this.time.getDate().toString() + Math.random().toString().slice(2,10);
            console.log(this.orderID);
            //统计商品的总金额和总数量
            let num = 0
            let sum = 0
            //从选中的商品中进行遍历循环,把每个商品的数量和金额进行相加
            this.multipleSelection.map(v=>{
                num += v.num
                sum += parseInt(v.total)
            })
            //打印检查数据是否正确
            console.log("num"+num);
            console.log("sum"+sum);
            //把相关的数据添加到store中的相关数组里
            this.store.orderAdd({
                orderID:this.orderID,
                time:this.time,
                num:this.num,
                sum:this.sum,
                isOrdered:false,//这个变量用来记录本订单是否已经完成支付
                child:[...this.multipleSelection]//展开运算符,通常用来把一个数组逐一进行操作，相当与进行了循环
            })
            //过程性检查,订单数组是否已经传递过去
            console.log(this.store.orderData);
            ElMessageBox.alert('已加入订单，请前往订单页面付款','温馨提示', {
                confirmButtonText:'知道了',
                callback: () => {
                    ElMessage({
                        type: 'info',
                        message: '订单加入成功',
                        })
                    },
                })
                //商品加入订单后要在购物车中进行删除
                this.multipleSelection.forEach((List)=>{
                    let x = this.cartData.findIndex((item)=>List.id == item.id)
                    this.cartData.splice(x,1)
                    sessionStorage.setItem('cart',JSON.stringify(this.cartData))
                })
            }
    },
    searchCart() { // 添加搜索方法
      this.cartData = JSON.parse(sessionStorage.getItem('cart'));
      if (this.search.trim()) {
        this.cartData = this.cartData.filter(item => {
          return Object.values(item).some(value => {
            return String(value).toLowerCase().includes(this.search.toLowerCase());
          });
        });
      } else {
        this.cartData = JSON.parse(sessionStorage.getItem('cart'));
      }
    }
  },
  watch: {
    search: function() { // 监听搜索关键词的变化
      this.searchCart();
    }
        },
    }
</script>